var _config=null;
$.ajax({
    type: 'GET',
    url: baseUrl+"/interface/getConfig2",
   xhrFields: {
   withCredentials: true
   },
   crossDomain: true,
    success: function(data){
       _config=data;
        
    //PC端钉钉配置    
   DingTalkPC.config({
    agentId : _config.agentid,
    corpId : _config.corpId,
    timeStamp : _config.timeStamp,
    nonceStr : _config.nonceStr,
    signature : _config.signature,
    jsApiList : ['biz.contact.choose',
        'device.notification.confirm', 'device.notification.alert',
        'device.notification.prompt', 'biz.ding.post',
        'biz.util.openLink' ]
});
        
    DingTalkPC.error(function(err) {
    alert('dd error: ' + JSON.stringify(err));
});
    
    //移动端钉钉配置
    dd.config({
			agentId : _config.agentid,
			corpId : _config.corpId,
			timeStamp : _config.timeStamp,
			nonceStr : _config.nonceStr,
			signature : _config.signature,
			jsApiList : ['biz.contact.complexPicker',
					'device.notification.confirm', 'device.notification.alert',
					'device.notification.prompt']
		});
   dd.error(function(err) {
    		alert('dd error: ' + JSON.stringify(err));
    	});     
    

    },error : function(xhr, errorType, error) {
	    logger.e("yinyien:" + _config.corpId);
	    alert(errorType + ', ' + error);
    }
});


$(function(){
    $("#header").load("header.html");
    winWid=$(window).width(); //屏幕宽
    percellWid=40,percellHet=50,cellContainHet=150;
    var addToken=Tool.addTokenToParams;
    var nameToIdObj=new Object();
    //初始化各个授权属性的人员
    $.ajax({
        type: 'GET',
        url: doGetUsers+'/all',
        contentType:"application/json;charset=UTF-8",
        xhrFields: {
        withCredentials: true
    		      },
        crossDomain: true,
        beforeSend:function(xhr){
            showLoading();
                },
        success: function(result){
            hideLoading();
            var msg=result.result_msg;
            if(msg=='success'){
                var data=result.data;
                var initFunc=function(data){
                    var manageArr=data.canmanage,adminArr=data.isadmin,submitArr=data.cansubmit,visitArr=data.canvisit;
                    var manageHtml='';
                    $.each(manageArr,function(index,elm){
                        var userName=elm.userName,userId=elm.userId,avatar=elm.avatarUrl;
                        nameToIdObj[userName]=userId;
                        if(avatar==''||avatar=='null')
                            avatar='../media/tx.jpg';
                        manageHtml+="<li><button  class='personAvatar' style='background-image: url("+avatar+")'></button><span>"+userName+"</span></li>";
                    });
                    $("#jhgl").prepend(manageHtml);
                    resizeContainTo($("#jhgl"),manageArr);
                    
                    var glyHtml='';
                    $.each(adminArr,function(index,elm){
                        var userName=elm.userName,userId=elm.userId,avatar=elm.avatarUrl;
                        nameToIdObj[userName]=userId;
                        if(avatar==''||avatar=='null')
                            avatar='../media/tx.jpg';
                        glyHtml+="<li><button  class='personAvatar' style='background-image: url("+avatar+")'></button><span>"+userName+"</span></li>";
                    });
                    $("#gly").prepend(glyHtml);
                    resizeContainTo($("#gly"),adminArr);
                    
                     var submitHtml='';
                    $.each(submitArr,function(index,elm){
                        var userName=elm.userName,userId=elm.userId,avatar=elm.avatarUrl;
                        nameToIdObj[userName]=userId;
                        if(avatar==''||avatar=='null')
                            avatar='../media/tx.jpg';
                        submitHtml+="<li><button  class='personAvatar' style='background-image: url("+avatar+")'></button><span>"+userName+"</span></li>";
                    });
                    $("#jhlr").prepend(submitHtml);
                    resizeContainTo($("#jhlr"),submitArr);
                    
                     var visitHtml='';
                    $.each(visitArr,function(index,elm){
                        var userName=elm.userName,userId=elm.userId,avatar=elm.avatarUrl;
                        nameToIdObj[userName]=userId;
                        if(avatar==''||avatar=='null')
                            avatar='../media/tx.jpg';
                        visitHtml+="<li><button  class='personAvatar' style='background-image: url("+avatar+")'></button><span>"+userName+"</span></li>";
                    });
                    $("#ckll").prepend(visitHtml);
                    resizeContainTo($("#ckll"),visitArr);
                };
                initFunc(data);
                avatarClickToRemove();
            }else
                alert('初始化失败，请重新进入');
                 
        },error : function(xhr, errorType, error) {
            hideLoading();
            alert(errorType + ', ' + error);   
    }});
    
    //添加头像后自适应大小
    function resizeContainTo(container,dataArray){
        var count=dataArray.length;
        var total_mj=(percellWid+5)*percellHet*count+20;
        var maxHet=total_mj/winWid/percellHet;
        var parent=container.parent();
        var toheight=(Math.ceil(maxHet)+1)*percellHet;
        if(toheight>percellHet){
            parent.css("min-height",toheight);
        }
        
    }
    
    //本功能不考虑同名用户的情况
    //
    //点击增加人员授权按钮
    $(".addbtn_cls").click(function(){
         var currentId=$(this).attr("id");
         var sibs=$(this).parent().siblings();
         var idarray=new Array();
         sibs.each(function(index,elm){
            var name=$(elm).children("span").text();
            var userId=nameToIdObj[name];
            if(typeof(userId)!="undefined"){
                idarray.push(userId);
            }  
         });
        //钉钉PC端 ready
         DingTalkPC.ready(function() {
        	 console.log("ready success");
           DingTalkPC.biz.contact.choose({
           multiple: true, //是否多选： true多选 false单选； 默认true
           users: idarray, //默认选中的用户列表，员工userid；成功回调中应包含该信息
           corpId:_config.corpId, //企业id
           max: 200, //人数限制，当multiple为true才生效，可选范围1-1500
           onSuccess: function(data) {
            showLoading();
            dealContactBackData(data,findRootParent(currentId));
           },
           onFail : function(err) {
        	   console.log("faild");
           }
          }); });
        
        //钉钉移动端 ready
        dd.ready(function() {
    	    dd.biz.contact.complexPicker({
                title:"选择人员",            
                corpId:_config.corpId,              
                multiple:true,            //是否多选
                limitTips:"超出了",          //超过限定人数返回提示
                maxUsers:200,            //最大可选人数
                pickedUsers:idarray,            //已选用户
                pickedDepartments:[],          //已选部门
                disabledUsers:[],            //不可选用户
                disabledDepartments:[],        //不可选部门
                requiredUsers:[],            //必选用户（不可取消选中状态）
                requiredDepartments:[],        //必选部门（不可取消选中状态）
                appId:_config.agentid,              //微应用的Id
                permissionType:"xxx",          //选人权限，目前只有GLOBAL这个参数
                responseUserOnly:false,        //返回人，或者返回人和部门
                startWithDepartmentId:0 ,   // 0表示从企业最上层开始，IOS不支持该字段
                onSuccess: function(result) {
                    showLoading();
                    dealContactBackData(result.users,findRootParent(currentId));        
                },
                onFail : function(err) {console.log("faild");}
            });
    		
    	});
        
        
    });
    
    function avatarClickToRemove(){
         $(".personAvatar").click(function(){
            var rootParent=$(this).parent().parent();
            var currentParent=$(this).parent();
            var name=$(this).next().text();
            var userId=nameToIdObj[name];
            var perType=getUserSetTypeByParentUlId(rootParent.attr('id'));
            var params={userId:userId};
            params[perType]="0";
             $.ajax({
    		  type: 'POST',
    		  url: doSetUser,
    		  contentType:"application/json;charset=UTF-8",
    		  data:JSON.stringify(addToken(params)),
    		  xhrFields: {
    		  withCredentials: true
    		           },
    		  crossDomain: true,
    		  success: function(result){
                  var msg=result.result_msg;
                  if(msg=='success')
                      currentParent.remove();
                  else
                      alert(msg);
    		  },error : function(xhr, errorType, error) {
    				alert(errorType + ', ' + error);
              }});
            
        });
    }
    
   
    function findRootParent(curentId){
        return $("#"+curentId).parent().parent();
    }
    function getPerTypeByParentUlId(pid){
        if(pid=='jhlr'){
            return 'cansubmit';
        }else if(pid=='jhgl'){
            return 'canmanage';
        }else if(pid=='ckll'){
            return 'canvisit';
        }else{
            return 'isadmin';
        }
    }
    function getUserSetTypeByParentUlId(pid){
        if(pid=='jhlr'){
            return 'isSubmit';
        }else if(pid=='jhgl'){
            return 'isManage';
        }else if(pid=='ckll'){
            return 'isVisit';
        }else{
            return 'isAdmin';
        }
    }
   
    function dealContactBackData(data,parentUl){
        var currentType=getPerTypeByParentUlId(parentUl.attr('id'));
        var childs=parentUl.children();
        childs.each(function(index,elm){
            if(index!=childs.length-1){
                $(elm).remove();
            }
        });
        var idArray=new Array();
        var avatarArray=new Array();
        var datacount=data.length;
        var params={userIds:'',perType:currentType};
        if(datacount==0){
            $.ajax({
    		  type: 'POST',
    		  url: doSetUsers,
    		  contentType:"application/json;charset=UTF-8",
    		  data:JSON.stringify(addToken(params)),
    		  xhrFields: {
    		  withCredentials: true
    		           },
    		  crossDomain: true,
    		  success: function(result){
                  hideLoading();
                  var msg=result.result_msg;
                  if(msg!='success')
                      alert(msg);
                  return;
    		  },error : function(xhr, errorType, error) {
                    hideLoading();
    				alert(errorType + ', ' + error);
                    return;
              }});
            
        }
        var innerHtml='';   
        for(var i=0;i<datacount;i++){
            var obj=data[i];
            innerHtml+="<li><button  class='personAvatar' style='background-image: url("+obj.avatar+")'></button><span>"+obj.name+"</span></li>";
            idArray.push(obj.emplId);
            avatarArray.push(obj.avatar);
            nameToIdObj[obj.name]=obj.emplId;
        }
        var userids=idArray.join();
        var avatars=avatarArray.join();
        var params={userIds:userids,perType:currentType,avatars:avatars};
         $.ajax({
    		  type: 'POST',
    		  url: doSetUsers,
    		  contentType:"application/json;charset=UTF-8",
    		  data:JSON.stringify(addToken(params)),
    		  xhrFields: {
    		  withCredentials: true
    		           },
    		  crossDomain: true,
    		  success: function(result){
                  hideLoading();
                  var msg=result.result_msg;
                  if(msg=='success'){
                      parentUl.prepend(innerHtml);
                      resizeContainTo(parentUl,data);
                  }
                  else
                      alert(msg);                  
                  avatarClickToRemove();
    		  },error : function(xhr, errorType, error) {
                    hideLoading();
    				alert(errorType + ', ' + error);   
              }});
    }
    
});